package org.ezplatform.office.meeting.memo.web.rest;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.ezplatform.cloud.api.component.attachment.AttachmentUtilsService;
import org.ezplatform.cloud.api.component.popuser.PopUserScopeUtilService;
import org.ezplatform.cloud.api.system.user.UserApiService;
import org.ezplatform.core.common.WebUser;
import org.ezplatform.core.pagination.PropertyFilter;
import org.ezplatform.core.service.BaseService;
import org.ezplatform.core.web.controller.BaseController;
import org.ezplatform.core.web.util.WebUtils;
import org.ezplatform.core.web.view.OperationResult;
import org.ezplatform.mobile.util.common.service.CommonService;
import org.ezplatform.office.meeting.common.util.MeetingSendMsgUtils;
import org.ezplatform.office.meeting.common.util.MeetingUtils;
import org.ezplatform.office.meeting.info.entity.ApplyRecord;
import org.ezplatform.office.meeting.info.service.ApplyRecordService;
import org.ezplatform.office.meeting.info.service.SignedInfoService;
import org.ezplatform.office.meeting.info.web.rest.ApplyRecordWebApiController;
import org.ezplatform.office.meeting.memo.entity.MemoInfo;
import org.ezplatform.office.meeting.memo.entity.MemoUserInfo;
import org.ezplatform.office.meeting.memo.service.MemoInfoService;
import org.ezplatform.office.meeting.memo.service.MemoUserInfoService;
import org.ezplatform.office.meeting.notice.service.NoticeInfoService;
import org.ezplatform.office.meeting.setting.boardroom.entity.BoardroomSet;
import org.ezplatform.office.meeting.setting.boardroom.service.BoardroomSetService;
import org.ezplatform.util.StringUtils;
import org.ezplatform.util.UuidUtils;
import org.ezplatform.util.ValidateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * @ClassName: memoInfoController
 * @Description: 会议纪要控制类
 */
@RestController
@RequestMapping(value = "/api/w/memoInfoController")
public class MemoInfoWebApiController extends BaseController<MemoInfo, String> {
	private final static Logger LOGGER = LoggerFactory.getLogger(MemoInfoWebApiController.class);
	@Autowired
	private MemoInfoService service;
	
	@Autowired
    private PopUserScopeUtilService popUserScopeUtilService;
	
	@Autowired
	private ApplyRecordService applyRecordService;
	
	@Autowired
	private AttachmentUtilsService attachmentUtilsService;

	@Autowired
	private NoticeInfoService noticeInfoService;
	
	@Autowired
    private SignedInfoService signedInfoService;
	
	@Autowired
	private BoardroomSetService boardroomSetService;
	
    @Autowired
    private MemoUserInfoService memoUserInfoService;

	@Autowired
	private MeetingSendMsgUtils meetingSendMsgUtils;
	
	@Autowired
	private UserApiService userApiService;
	
	@Autowired
	private MeetingUtils meetingUtils;
	
	@Autowired
	private CommonService commonService;

	/*
	 * (非 JAVADOC) <p>Title: getEntityService</p> <p>Description: </p>
	 * 
	 * @return
	 * 
	 */
	@Override
	protected BaseService<MemoInfo, String> getEntityService() {
		return service;
	}

	/**
	 * 
	 * @Title: prepareModel
	 * @Description: 初始化数据
	 * @param request
	 * @param model
	 * @param id
	 * @return void
	 * @throws
	 */
	@ModelAttribute
	public void prepareModel(HttpServletRequest request, Model model,
			@RequestParam(value = "id", required = false) String id) {
		super.initPrepareModel(request, model, id);
	}

	@RequestMapping(value = "/entityIsExist", method = RequestMethod.POST)
	public OperationResult entityIsExist(String id) {
		MemoInfo entity = this.service.findOne(id);
		if(entity == null) return OperationResult.buildSuccessResult("notExist");
		else return OperationResult.buildSuccessResult("exist");
	}
	
	/**
	 * 获取列表数据(分页)
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getPageIsView", method = RequestMethod.GET)
    public Page getInfoPageIsView(HttpServletRequest request) {
		WebUser user = WebUtils.getCurrentUser();
		Pageable pageable = PropertyFilter.buildPageableFromHttpRequest(request);
		String title = ValidateUtils.filter(request.getParameter("title"));
		return service.findByPage(pageable, user.getUserId(), user.getCorpId(), title, 1);
    }
	
	/**
	 * 获取列表数据(分页)
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getPageNotView", method = RequestMethod.GET)
    public Page getInfoPageNotView(HttpServletRequest request) {
		WebUser user = WebUtils.getCurrentUser();
		Pageable pageable = PropertyFilter.buildPageableFromHttpRequest(request);
		String title = ValidateUtils.filter(request.getParameter("title"));
		return service.findByPage(pageable, user.getUserId(), user.getCorpId(), title, 0);
    }
	
	/**
     * 保存/修改
     *
     * @param entity
     * @param model
     * @return
     */
    @RequestMapping(value = "/editSave", method = RequestMethod.POST)
    public OperationResult editSave(@ModelAttribute("entity") MemoInfo entity, Model model,HttpServletRequest request) {
    	LOGGER.debug("-------------MemoInfoWebApi-editSave------------");
    	WebUser user = WebUtils.getCurrentUser();
        String corpId = user.getCorpId();
    	String memoUserJsonStr = StringUtils.null2String(request.getParameter("memoUserJsonStr"));
    	LOGGER.debug("---memoUserJsonStr:"+memoUserJsonStr);
    	long time=System.currentTimeMillis();
		entity.setMemoUser(saveScope(memoUserJsonStr, StringUtils.null2String(entity.getMemoUser()), "memo_scope"));
		LOGGER.debug("-------zhaozy1:"+(System.currentTimeMillis()-time));
    	time=System.currentTimeMillis();
    	ApplyRecord applyRecord = this.applyRecordService.findOne(entity.getApplyRecordId());
    	LOGGER.debug("-------zhaozy2:"+(System.currentTimeMillis()-time));
    	time=System.currentTimeMillis();
    	if(applyRecord == null) return OperationResult.buildFailureResult("当前数据已删除");
    	String id = entity.getId();
    	LOGGER.debug("---id:"+id);
    	LOGGER.debug("-------zhaozy3:"+(System.currentTimeMillis()-time));
    	time=System.currentTimeMillis();
    	OperationResult result = super.editSave(entity);
    	LOGGER.debug("-------zhaozy4:"+(System.currentTimeMillis()-time));
    	time=System.currentTimeMillis();
    	LOGGER.debug("---result:"+result.getMessage());
    	List<String> userIdList = this.service.getMemoInfoUserList(applyRecord, entity, TOKEN);
    	LOGGER.debug("-------zhaozy5:"+(System.currentTimeMillis()-time));
    	time=System.currentTimeMillis();
    	LOGGER.debug("---userIdList:"+userIdList.size());
    	//编辑时需要检测纪要通知的人有没有增减
        List<String> addList = new ArrayList<String>();
    	try {
	        
	        if(StringUtils.isNotEmpty(id)){
	        	List<MemoUserInfo> memoUserInfoList = memoUserInfoService.getMemoUserInfoByMemoId(id, corpId);
	        	LOGGER.debug("-------zhaozy6:"+(System.currentTimeMillis()-time));
	        	time=System.currentTimeMillis();
				List<MemoUserInfo> deleteList = new ArrayList<MemoUserInfo>();
				List<String> ids = new ArrayList<String>();
				for(MemoUserInfo mui : memoUserInfoList) {
					//老的id不在新的id集合里面，说明已删除
					if(!userIdList.contains(mui.getMemoUserId())) {
						deleteList.add(mui);
					}
					ids.add(mui.getMemoUserId());
				}
				for(String userId : userIdList) {
					//老的id集合不包含新的id，说明新的id是新增的
					if(!ids.contains(userId)) {
						addList.add(userId);
					}
				}
				LOGGER.debug("--deleteList.size()："+deleteList.size());
				if(deleteList!=null&&deleteList.size()>0) this.memoUserInfoService.delete(deleteList);
				LOGGER.debug("-------zhaozy7:"+(System.currentTimeMillis()-time));
		    	time=System.currentTimeMillis();
				LOGGER.debug("--addList.size()："+addList.size());
				if(addList!=null&&addList.size()>0) {
					this.memoUserInfoService.addMemoUserInfo(entity.getId(), addList, corpId);
					LOGGER.debug("-------zhaozy8:"+(System.currentTimeMillis()-time));
			    	time=System.currentTimeMillis();
				}
	        }else {
	        	addList.addAll(userIdList);
	        	LOGGER.debug("--userIdList.size()："+userIdList.size());
	        	if(userIdList!=null&&userIdList.size()>0) {
	        		this.memoUserInfoService.addMemoUserInfo(entity.getId(), userIdList, corpId);
	        		LOGGER.debug("-------zhaozy9:"+(System.currentTimeMillis()-time));
	            	time=System.currentTimeMillis();
	        	}
	        	String createdUserId = applyRecord.getCreatedBy();
	        	//会议发起人也能发起看见会议纪要
	        	if(!addList.contains(createdUserId)) {
	            	MemoUserInfo m = new MemoUserInfo();
	                m.setMemoId(entity.getId());
	                m.setMemoUserId(createdUserId);
	                m.setIsView(0);
	                m.setCorpId(corpId);
	                memoUserInfoService.save(m);
	                LOGGER.debug("-------zhaozy10:"+(System.currentTimeMillis()-time));
	            	time=System.currentTimeMillis();
	        	}
	        }
	        LOGGER.debug("---addList.size():"+addList.size());
    	} catch (Exception e) {
			e.printStackTrace();
			LOGGER.debug("---err-----");
    	}
        
    	Map<String, Object> ds = new HashMap<>();
    	ds.put("type", 5);
		ds.put("applyRecordId", applyRecord.getId());
		ds.put("meetingTitle", applyRecord.getName());
		ds.put("id", entity.getId());
		ds.put("userId", user.getUserId());
		ds.put("userName", user.getCnName());
		ds.put("userOrg", user.getOrgId());
		StringBuffer ids = new StringBuffer();
		StringBuffer jsonIds = new StringBuffer("[");
		for(int i = 0; i < addList.size(); i++) {
			if(i == addList.size() - 1) {
				ids.append(addList.get(i));
				jsonIds.append("{\"10\":\"" + addList.get(i) + "\"}");
			}else {
				ids.append(addList.get(i) + ",");
				jsonIds.append("{\"10\":\"" + addList.get(i) + "\"},");
			}
		}
		jsonIds.append("]");
		LOGGER.debug("---jsonIds:"+jsonIds);
		ds.put("userIds", ids.toString());
		ds.put("orgIds", "");
		LOGGER.debug("---ids:"+ids);
		if(!"".equals(ids.toString())) {
			boolean mobilePush = false;
	        boolean emailPush = false;
	        boolean smsPublish = false;
			String mesgPush = applyRecord.getMessagePush();
			if(StringUtils.isNotEmpty(mesgPush) && mesgPush.contains("mobile")) mobilePush = true;
			if(StringUtils.isNotEmpty(mesgPush) && mesgPush.contains("email")) emailPush = true;
			if(StringUtils.isNotEmpty(mesgPush) && mesgPush.contains("sms")) smsPublish = true;
			this.meetingSendMsgUtils.sendMail(ds, emailPush, corpId, TOKEN);
			this.meetingSendMsgUtils.sendMsgToApp(ds, mobilePush, corpId, TOKEN, request);
			this.meetingSendMsgUtils.sendSMS(ds, smsPublish, corpId, TOKEN);
		}
		LOGGER.debug("-------zhaozy11:"+(System.currentTimeMillis()-time));
    	time=System.currentTimeMillis();
		if(!"[]".equals(ids.toString()))this.meetingSendMsgUtils.sendMessage(ds, jsonIds.toString(), corpId, TOKEN);
		LOGGER.debug("-------zhaozy12:"+(System.currentTimeMillis()-time));
    	time=System.currentTimeMillis();
		LOGGER.debug("--result："+result);
    	return  result;
    }
	
    /**
	 * 选人组件信息保存到scope表
	 * @param jsonStr        json串
	 * @param fieldDataValue entity中的关联scope表的fieldDataValue字段的值
	 * @param fieldData      scope表的fieldData字段的值
	 * @return
	 */
	private String saveScope(String jsonStr, String fieldDataValue, String fieldData) {
		String scopeCode = StringUtils.null2String(fieldDataValue);
		if ("".equals(scopeCode)) {
			scopeCode = UuidUtils.UUID();
		}
		this.popUserScopeUtilService.saveScopeData("oa_meeting_apply_record_scope", scopeCode, jsonStr, "oa_meeting_memo_info", fieldData);
		return scopeCode;
	}
	
	/**
     * 编辑页面
     * 
     * @param model
     * @return
     */
    @RequestMapping(value = "/editShow", method = RequestMethod.GET)
    public Map<String, Object> editShow(HttpServletRequest request) {
        WebUser user = WebUtils.getCurrentUser();
        String corpId = "";
        if (user != null) {
            corpId = user.getCorpId();
        }
        String id = ValidateUtils.filter(request.getParameter("id"));
        String applyrecordId = ValidateUtils.filter(request.getParameter("applyrecordId"));
        
        Map<String, Object> result = new HashMap<>();

        MemoInfo memoInfo = this.service.findOne(id);
        if(memoInfo == null) {
        	result.put("entityIsDelete", true);
        	return result;
        }else {
        	result.put("entityIsDelete", false);
        }
        result.put("entity", memoInfo);
        //查询会议信息
        ApplyRecord applayRecord = this.applyRecordService.findOne(applyrecordId);
        result.put("applayRecord", applayRecord);
        
        // 纪要员
        String arMemoUser = popUserScopeUtilService.getScopeTypeValue("oa_meeting_apply_record_scope", "oa_meeting_apply_record",
                "memo_user", StringUtils.null2String(applayRecord.getMemoUser()));
        result.put("arMemoUser", arMemoUser);
        if (StringUtils.isNotEmpty(arMemoUser)) {
            String scopeName = this.userApiService.getScopeName(arMemoUser, corpId, TOKEN);
            result.put("arMemoUserName", scopeName);
        }
        String memoUserCode = this.popUserScopeUtilService.getScopeTypeValue(
        		"oa_meeting_apply_record_scope","oa_meeting_memo_info", "memo_scope", StringUtils.null2String(memoInfo.getMemoUser()));
        result.put("memoUserCode", memoUserCode);
        //塞入附件信息
        result.put("fileList", service.getAttachmentName(memoInfo.getFileId()));
        String sysWatermark = commonService.getSysParamValueByMark(corpId, TOKEN, "sysWatermark");
        if(StringUtils.isNotBlank(sysWatermark) && sysWatermark.contains("meetingMemo"))
        	 result.put("watermark", "1");
        else result.put("watermark", "0");
        return result;
    }
    
    @RequestMapping(value = "/getSysWatermark", method = RequestMethod.GET)
    public String getSysWatermark(HttpServletRequest request) {
    	WebUser user = WebUtils.getCurrentUser();
    	String sysWatermark = commonService.getSysParamValueByMark(user.getCorpId(), TOKEN, "sysWatermark");    
    	if(StringUtils.isNotBlank(sysWatermark) && sysWatermark.contains("meetingMemo"))
    		return "1";
    	else return "0";
    }
    
    /**
     * 查看页面
     * 
     * @param model
     * @return
     */
    @RequestMapping(value = "/viewShow", method = RequestMethod.GET)
    public Map<String, Object> viewShow(HttpServletRequest request) {
        WebUser user = WebUtils.getCurrentUser();
        String corpId = "";
        if (user != null) {
            corpId = user.getCorpId();
        }
        String id = ValidateUtils.filter(request.getParameter("id"));
        String applyrecordId = ValidateUtils.filter(request.getParameter("applyrecordId"));
        
        Map<String, Object> result = new HashMap<>();

        MemoInfo memoInfo = this.service.findOne(id);
        if(memoInfo == null) {
        	result.put("entityIsDelete", true);
        	return result;
        }else {
        	result.put("entityIsDelete", false);
        }
        result.put("entity", memoInfo);
        //塞入附件信息
        result.put("fileList", service.getAttachmentName(memoInfo.getFileId()));
        //查询会议信息
        ApplyRecord applyRecord = this.applyRecordService.findOne(applyrecordId);
        result.put("applyRecord", applyRecord);
        
        // 主持人
        String emceeUser = popUserScopeUtilService.getScopeTypeValue("oa_meeting_apply_record_scope", "oa_meeting_apply_record",
                "emcee_user", StringUtils.null2String(applyRecord.getEmceeUser()));
        result.put("emceeUser", emceeUser);
        if (StringUtils.isNotEmpty(emceeUser)) {
//            String scopeName = this.userApiService.getScopeName(emceeUser, corpId, TOKEN);
        	String scopeName = applyRecordService.getScopeName("oa_meeting_apply_record", applyRecord.getEmceeUser(), "emcee_user");
            result.put("emceeUserName", scopeName);
        }
        
        // 纪要员
        String arMemoUser = popUserScopeUtilService.getScopeTypeValue("oa_meeting_apply_record_scope", "oa_meeting_apply_record",
                "memo_user", StringUtils.null2String(applyRecord.getMemoUser()));
        result.put("arMemoUser", arMemoUser);
        if (StringUtils.isNotEmpty(arMemoUser)) {
//        	String scopeName = this.userApiService.getScopeName(arMemoUser, corpId, TOKEN);
        	String scopeName = applyRecordService.getScopeName("oa_meeting_apply_record", applyRecord.getMemoUser(), "memo_user");
            result.put("arMemoUserName", scopeName);
        }
        
        String attendUserName = "";
        String noAttendUserName = "";
        int isSigned = applyRecord.getIsSigned();
        if(isSigned==0){//会议签到：未开启
            //查询确认参会人员
            attendUserName = this.noticeInfoService.getNoticeUserName(applyRecord.getId(),1);
            //查询未确认参会人员
            noAttendUserName = this.noticeInfoService.getNoticeUserName(applyRecord.getId(),0);
        }else{//会议签到：开启
          //查询签到参会人员
            attendUserName = this.signedInfoService.getSignedUserName(applyRecord.getId(),1);
            //查询未签到参会人员
            noAttendUserName = this.signedInfoService.getSignedUserName(applyRecord.getId(),0);
        }
        result.put("attendUserName", attendUserName);
        result.put("noAttendUserName", noAttendUserName);
        if(StringUtils.isNotEmpty(applyRecord.getBoardroomId())) {
        	 //查询会议室信息
            BoardroomSet boardroomSet = this.boardroomSetService.findOne(applyRecord.getBoardroomId());
            result.put("boardroomSet", boardroomSet);
        }else {
        	result.put("boardroomSet", new BoardroomSet());
        }
        //修改会议纪要月度状态
        this.memoUserInfoService.editMemoUserInfo(memoInfo.getId(),user.getUserId());
        String sysWatermark = commonService.getSysParamValueByMark(corpId, TOKEN, "sysWatermark");
        if(StringUtils.isNotBlank(sysWatermark) && sysWatermark.contains("meetingMemo"))
        	 result.put("watermark", "1");
        else result.put("watermark", "0");
        return result;
    }
    
    /**
     * 获取附件信息
     * @return
     */
    @RequestMapping(value = "/getFileData", method = RequestMethod.GET)
    public String getFileData(HttpServletRequest request){
        String ids = ValidateUtils.filter(request.getParameter("ids"));
        String fileInfo="";
        if(StringUtils.isNotBlank(ids)){
          fileInfo = attachmentUtilsService.getAttachmentInfo(ids, TOKEN);
        }
        return fileInfo;
    }
    
	private Map<String, String> transformUserScopePlatform2Dd(String fieldDataValue, String fieldData, String corpId, String token){
        String ids = "", jsonIds = "";
        Map<String, String> result = new HashMap<>();
        String scopeTypeStr = this.popUserScopeUtilService.getScopeTypeValue("oa_meeting_apply_record_scope", "oa_meeting_apply_record", fieldData, StringUtils.null2String(fieldDataValue));
        String[] scopeTypeArray = scopeTypeStr.split(",");
        if(scopeTypeArray != null && scopeTypeArray.length>0) {
        	List<String> l = new ArrayList<>();
            for (int i = 0; i < scopeTypeArray.length; i++) {
                String[] info = scopeTypeArray[i].split("SCOPE");
                if (info.length > 1){
                	String id  = info[1];
                	String type  = info[0];
                	List<String> u = new ArrayList<>();
                	if("user".equals(type)){
                        jsonIds +="{\"10\":\""+id+"\"},";
                        l.add(id);
//                		u = this.userApiService.getUserIdBySysOrThird(id, "1", "DD", corpId, token);
                	}
//                    if(u!=null && u.size()>0){
//                    	l.addAll(u);
//                    }
                }
            }
            if(l!=null && l.size()>0){
            	for(int i=0; i<l.size(); i++){
            		String thirdId = l.get(i);
            		if(StringUtils.isNotEmpty(thirdId)){
            			ids += thirdId + ",";
            		}
            	}
            }
        }
        result.put("jsonIds", jsonIds);
        result.put("ids", ids);
        return result;
    }
	
	private Map<String, String> transformUOScopePlatform2Dd(String fieldDataValue, String fieldData, String corpId, String token){
		Map<String, String> map = new HashMap<>();
		String ids = "", orgIds = "", jsonIds = "";
        String scopeTypeStr = this.popUserScopeUtilService.getScopeTypeValue("oa_meeting_apply_record_scope", "oa_meeting_apply_record", fieldData, StringUtils.null2String(fieldDataValue));
        String[] scopeTypeArray = scopeTypeStr.split(",");
        if(scopeTypeArray != null && scopeTypeArray.length>0) {
        	List<String> l = new ArrayList<>();
        	List<String> o = new ArrayList<>();
            for (int i = 0; i < scopeTypeArray.length; i++) {
                String[] info = scopeTypeArray[i].split("SCOPE");
                if (info.length > 1){
                	String id  = info[1];
                	String type  = info[0];
                	if("user".equals(type)){
                        jsonIds +="{\"10\":\""+id+"\"},";
                        l.add(id);
//                		List<String> u = this.userApiService.getUserIdBySysOrThird(id, "1", "DD", corpId, token);
//                		if(u!=null && u.size()>0){
//                        	l.addAll(u);
//                        }
                	}else if("org".equals(type)){
                        jsonIds +="{\"20\":\""+id+"\"},";
                        o.add(id);
//                		List<String> u = this.orgApiService.getOrgIdOrThirdUid(id, "1", "DD", corpId, token);
//                		if(u!=null && u.size()>0){
//                            for(int j=0; j<u.size(); j++){
//                                if("1".equals(u.get(j))){
//                                    Map<String, Object> topOrgInfo = this.orgApiService.getPopuOrgChildInfo(id,"user", "","", "", corpId, token);
//                                    List<Map<String, Object>> userList = (List<Map<String, Object>>)topOrgInfo.get("userList");
//                                    List<Map<String, Object>> orgList = (List<Map<String, Object>>)topOrgInfo.get("orgList");
//                                    if(userList!=null && userList.size()>0){
//                                        for(int k=0; k<userList.size(); k++){
//                                            Map<String, Object> map1 = userList.get(k);
//                                            String ddUId = StringUtils.null2String(map1.get("ddUId"));
//                                            if(StringUtils.isNotEmpty(ddUId)){
//                                                l.add(ddUId);
//                                            }
//                                        }
//                                    }
//                                    if(orgList!=null && orgList.size()>0){
//                                        for(int k=0; k<orgList.size(); k++){
//                                            Map<String, Object> map1 = orgList.get(k);
//                                            String ddUId = StringUtils.null2String(map1.get("ddUId"));
//                                            if(StringUtils.isNotEmpty(ddUId)){
//                                                o.add(ddUId);
//                                            }
//                                        }
//                                    }
//                                }else{
//                                    o.add(u.get(j));
//                                }
//                            }
//                        }
                	}
                }
            }
            if(l!=null && l.size()>0){
            	for(int i=0; i<l.size(); i++){
            		String thirdId = l.get(i);
            		if(StringUtils.isNotEmpty(thirdId)){
            			ids += thirdId + ",";
            		}
            	}
            }
            
            if(o!=null && o.size()>0){
            	for(int i=0; i<o.size(); i++){
            		String thirdId = o.get(i);
            		if(StringUtils.isNotEmpty(thirdId)){
            			orgIds += thirdId + ",";
            		}
            	}
            }
        }
        map.put("jsonIds", jsonIds);
        map.put("userIds", ids);map.put("orgIds", orgIds);
        return map;
    }
	
	private Map<String, String> transformUOSGScopePlatform2Dd(String fieldDataValue, String fieldData, String corpId, String token){
		Map<String, String> map = new HashMap<>();
		String ids = "", orgIds = "", jsonIds = "";
        String scopeTypeStr = this.popUserScopeUtilService.getScopeTypeValue("oa_meeting_apply_record_scope", "oa_meeting_memo_info", fieldData, StringUtils.null2String(fieldDataValue));
        String[] scopeTypeArray = scopeTypeStr.split(",");
        if(scopeTypeArray != null && scopeTypeArray.length>0) {
            for (int i = 0; i < scopeTypeArray.length; i++) {
                String[] info = scopeTypeArray[i].split("SCOPE");
                if (info.length > 1){
                	String id  = info[1];
                	String type  = info[0];
                	if("user".equals(type)){
                        jsonIds +="{\"10\":\""+id+"\"},";
                        ids += id + ",";
                	}else if("org".equals(type)){
                        jsonIds +="{\"20\":\""+id+"\"},";
                        orgIds += id + ",";
                	}else if("group".equals(type)){
                		List<String> groupUserList = this.userApiService.getUserIdsByGrpId(id, "1", corpId, token);
                		if(CollectionUtils.isNotEmpty(groupUserList)) {
                			for(String gu : groupUserList) {
                				jsonIds +="{\"10\":\""+gu+"\"},";
                                ids += gu + ",";
                			}
                		}
                	}else if("station".equals(type)){
                		List<String> stationUserList = this.userApiService.getUserIdsByStationId(id, "1", corpId, token);
                		if(CollectionUtils.isNotEmpty(stationUserList)) {
                			for(String su : stationUserList) {
                				jsonIds +="{\"10\":\""+su+"\"},";
                                ids += su + ",";
                			}
                		}
                	}
                }
            }
        }
        map.put("jsonIds", jsonIds);
        map.put("userIds", ids);
        map.put("orgIds", orgIds);
        return map;
    }
	
	/**
     * 转发功能
     * @return
     */
    @RequestMapping(value = "/transmitMemo", method = RequestMethod.POST)
    public OperationResult transmitMemo(String memoId, String jsonStrTransmiScope) {
    	Map failureMap = new HashMap();
    	try {
			WebUser user = WebUtils.getCurrentUser();
			String corpId = user.getCorpId();
			String token = user.getJwtToken();
			List<String> addList = null;
			if(StringUtils.isNotEmpty(jsonStrTransmiScope)) {
				JSONArray json = (JSONArray) JSONArray.parse(jsonStrTransmiScope);
			    if(json != null) {
			    	String userId = "", orgId = "", type = "";
			    	Set<String> userIdList = new HashSet<String>();
			    	for(int i = 0; i < json.size(); i++) {
			    		JSONObject jo = (JSONObject)json.get(i);
			    		type = jo.getString("scopeType");
			    		if("user".equals(type)) {
			    			userId = jo.getString("scopeValue");
			    			userIdList.add(userId);
			    		}else if("org".equals(type)) {
			    			orgId = jo.getString("scopeValue");
			    			List<String> unitUserList = this.userApiService.getUserIdsByOrgId(orgId, "", "1", corpId, token);
			                if(unitUserList!=null && unitUserList.size()>0){
			                	userIdList.addAll(unitUserList);
			                }
			    		}
			    	}
			    	addList = new ArrayList<String>(userIdList);
			    }
			    this.memoUserInfoService.addMemoUserInfo(memoId, addList, corpId);
			}
			failureMap.put("i18NCode", "oa.meeting.tip48");
			return OperationResult.buildSuccessResult("转发成功",failureMap);
		} catch (Exception e) {
			e.printStackTrace();
			failureMap.put("i18NCode", "oa.meeting.tip49");
			return OperationResult.buildFailureResult("转发失败",failureMap);
		}
    }
    
    /**
     * 删除会议纪要
     * @return
     */
    @RequestMapping(value = "/deleteMemoInfo", method = RequestMethod.POST)
    public OperationResult deleteMemoInfo(String memoId) {
    	WebUser user = WebUtils.getCurrentUser();
		String corpId = user.getCorpId();
		List<MemoUserInfo> list = this.memoUserInfoService.getMemoUserInfoByMemoId(memoId, corpId);
		this.memoUserInfoService.delete(list);
		return this.delete(memoId);
    }
    
	/**
     * 删除功能
     * @return
     */
    @RequestMapping(value = "/deleteUserInfoMemoInfo", method = RequestMethod.POST)
    public OperationResult deleteUserInfoMemoInfo(@RequestParam("ids") String... ids) {
    	Map failureMap = new HashMap();
    	List<MemoUserInfo> muiList = memoUserInfoService.findAll(ids);
    	if(CollectionUtils.isNotEmpty(muiList)) {
    		memoUserInfoService.delete(muiList);
    		failureMap.put("i18NCode", "oa.personal.deletesuccess");
    		return OperationResult.buildSuccessResult("删除成功",failureMap);
    	}else {
    		failureMap.put("i18NCode", "oa.personal.deletefal");
    		return OperationResult.buildFailureResult("删除失败",failureMap);
    	}
    }
	
}
